<template>
  <el-row>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-form-item prop="role">
          <el-select v-model="this.selectRole" placeholder="选择角色" clearable>
            <el-option
                v-for="item in roles"
                :key="item.key"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="lookUserByRole(this.selectRole)"
        >搜索
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="this.deleteUsers(this.deleteUserIds)"
        >批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </el-row>
  <el-row>
    <el-col>
      <el-table
          height="500"
          :data="tableData"
          border
          @selection-change="getUserIds"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column
            v-for="column in this.tableColumn"
            :key="column.index"
            :label="column.label"
            :prop="column.prop"
            :width="defaultColumn"
            align="center"
        ><!-- 状态列特殊处理 -->
          <template #default="scope" v-if="column.prop === 'status'">
            <el-tag
                class="ml-2"
                :type="scope.row.status === 0 ? 'success' : 'danger'"
            >{{ scope.row.status === 0 ? "正常" : "失效" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button size="small" @click="this.updateUserClick(scope.row)"
            >修改
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="deleteOneUser(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <el-row>
    <el-col></el-col>
  </el-row>
  <!-- 修改用户 -->
  <el-dialog
      v-model="updateDialogVisible"
      title="修改用户"
      width="30%"
      center
      draggable
  >
    <el-form
        :model="updateUserForm"
        :rules="userRule"
        ref="updateUser"
        @keyup.enter="this.updateOneUser(this.updateUserForm)"
    >
      <el-form-item prop="name" label="用户名">
        <el-input v-model="this.updateUserForm.name"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input v-model="this.updateUserForm.phone"></el-input>
      </el-form-item>
      <el-form-item prop="status" label="封禁操作">
        <el-radio-group v-model="this.updateUserForm.status">
          <el-radio-button label="0" border>解封</el-radio-button>
          <el-radio-button label="1" border>封禁</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="role" label="角色">
        <el-select
            v-model="this.updateUserForm.role"
            placeholder="选择角色"
            clearable
        >
          <el-option
              v-for="item in roles"
              :key="item.key"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="address" label="地址">
        <el-select
            v-model="this.updateUserForm.address"
            placeholder="选择地址"
            clearable
        >
          <el-option
              v-for="item in addresses"
              :key="item.key"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="this.updateOneUser(this.updateUserForm)"
      >修改
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import {
  lookAllUser,
  updateCurrentUser,
  deleteUsers,
  lookUserByRole,
} from "../api/user";
import {lookAllRoles} from "../api/role";
import {lookAllAddresses} from "../api/address";

export default {
  data() {
    return {
      //表格数据
      tableData: [],
      //查询的角色ID
      selectRole: "",
      //修改时需要的表单元素
      updateUserForm: {
        name: "",
        role: "",
        status: "",
        address: "",
        phone: "",
      },
      //修改对话框是否显示
      updateDialogVisible: false,
      //批量删除时的id集合
      deleteUserIds: [],
      //角色信息
      roles: [],
      //地址
      addresses: [],
      //表单校验
      userRule: {
        //姓名
        name: [
          {
            required: true,
            message: "用户名不得为空!",
            trigger: "blur",
          },
        ],
        //状态
        status: [
          {
            required: true,
            message: "请指定用户当前状态!",
            trigger: "blur",
          },
        ],
        //角色
        role: [
          {
            required: true,
            message: "请选择角色!",
            trigger: "blur",
          },
        ],
        //地址
        address: [
          {
            required: true,
            message: "请选择地址!",
            trigger: "blur",
          },
        ],
        //手机号
        phone: [
          {
            required: true,
            message: "请输入手机号!",
            trigger: "blur",
          },
          {
            required: true,
            validator: (rule, value, callback) => {
              if (
                  !/^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/.test(
                      value
                  )
              ) {
                callback(new Error("请输入正确的手机号!"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      //列宽
      defaultColumn: 160,
      //表格列名集合
      tableColumn: [
        {
          index: 1,
          label: "编号",
          prop: "id",
        },
        {
          index: 2,
          label: "用户名",
          prop: "name",
        },
        {
          index: 3,
          label: "状态",
          prop: "status",
        },
        {
          index: 4,
          label: "手机号",
          prop: "phone",
        },
      ],
    };
  },
  created() {
    this.lookAllUser();
    this.lookAllRoles();
    this.lookAllAddresses();
  },
  methods: {
    //查看所有用户逻辑
    lookAllUser() {
      lookAllUser().then((req) => {
        this.tableData = req.data.data;
        console.log(this.tableData);
      });
    },
    //根据角色查询用户
    lookUserByRole(role) {
      console.log(role);
      if (role === "") {
        this.lookAllUser();
        return;
      }
      lookUserByRole(role).then((req) => {
        this.tableData = req.data.data;
      });
    },
    //查看所有地址逻辑
    lookAllAddresses() {
      lookAllAddresses().then((req) => {
        var address = req.data.data;
        for (let i = 0; i < address.length; i++) {
          var a = {
            key: i,
            value: address[i].id,
            label: `${address[i].schoolName}${address[i].floor}${address[i].ridgepole}栋${address[i].layer}层${address[i].number}号`,
          };
          this.addresses.push(a);
        }
        console.log(this.addresses);
      });
    },
    //查询所有角色
    lookAllRoles() {
      lookAllRoles().then((req) => {
        var roles = req.data.data;
        for (let i = 0; i < roles.length; i++) {
          var a = {
            key: i,
            value: roles[i].id,
            label: roles[i].roleName,
          };
          this.roles.push(a);
        }
        console.log(this.roles);
      });
    },
    //修改一名用户
    updateOneUser(obj) {
      console.log(obj);
      this.$refs["updateUser"].validate((valid) => {
        if (valid) {
          updateCurrentUser(obj).then((req) => {
            if (req.data.success) {
              this.$message({
                type: "success",
                message: "修改用户成功!",
                showClose: true,
              });
              this.updateDialogVisible = false;
              this.lookAllUser();
            } else {
              this.$message({
                type: "error",
                message: "修改用户失败!",
                showClose: true,
              });
            }
          });
        }
      });
    },
    //删除一条用户信息
    deleteOneUser(ids) {
      var id = [ids];
      var user = sessionStorage.getItem("user");
      this.$confirm("你真的要删除这条用户的信息吗?(真的永久)", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //非法删除判断
        if (ids.toString() === user) {
          this.$message({
            type: "error",
            message: "不能删除自己哦!",
            showClose: true,
          });
          return;
        }
        deleteUsers(id).then((req) => {
          if (req.data.success) {
            this.$message({
              type: "success",
              message: "删除用户成功!",
              showClose: true,
            });
            this.lookAllUser();
          } else {
            this.$message({
              type: "error",
              message: "删除用户失败!",
              showClose: true,
            });
          }
        });
      });
    },
    //批量删除
    deleteUsers(ids) {
      this.$confirm(`你真的要删除${ids.length}条用户的信息吗?(真的永久)`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteUsers(ids).then((req) => {
          if (req.data.success) {
            this.$message({
              type: "success",
              message: "删除用户成功!",
              showClose: true,
            });
            this.lookAllUser();
          } else {
            this.$message({
              type: "error",
              message: "删除用户失败!",
              showClose: true,
            });
          }
        });
      });
    },
    //修改用户前的附加操作
    updateUserClick(obj) {
      console.log(obj);
      this.updateUserForm = obj;
      this.updateDialogVisible = true;
    },
    //获取选中的Id值
    getUserIds(val) {
      var ids = [];
      for (let i = 0; i < val.length; i++) {
        ids[i] = val[i].id;
      }
      this.deleteUserIds = ids;
    },
  },
};
</script>

<style>
</style>